# TODO: Add comment
# 
# Author: guochun
###############################################################################



Km=function(ppp,fun,r=NULL,br=NULL,nullmodel=c("weighted","correlation"),mc.cores=1){
	nd=100
	fun=eval(fun)
	ppp=unique(ppp)
	x=ppp$x
	y=ppp$y
	ds=as.matrix(stats::dist(matrix(c(x,y),ncol=2)))
	lambda=ppp$n/area.owin(ppp$window)
	
	maxx=max(x)
	maxy=max(y)
	#step1: minimum distance to the border
	xlow=pmin(x,maxx-x)
	ylow=pmin(y,maxy-y)
	xylow=pmin(xlow,ylow)
	
	if(is.null(r)){
		rmax=min(maxx,maxy)/4
		r=seq(0,rmax,length.out=nd)
	}
	if(is.null(br)){
		sel=max(r)<xylow
	}else{
		sel=xylow>br
	}
	
	temp=numeric()
	for (i in 2:length(r)){
		dend=r[i]
		sel=xylow>dend
		if(mc.cores==1){
			temp[i-1]=mean(apply(ds[sel,],1,markline,dend=dend,
							marks=ppp$marks,fun=fun),na.rm=TRUE)
		}else{
			temp[i-1]=mean(mclapply(ds[sel,],1,markline,dend=dend,
							marks=ppp$marks,fun=fun,mc.cores=mc.cores),na.rm=TRUE)
		}
		
	}
	result=data.frame(r=r[-1],pk=temp/lambda)
	return(result)
}

markline=function(x,dend,marks,fun){
	selecti=which(x==0)
	marki=marks[selecti]
	selectj= x<=dend & x!=0
	
	if(any(selectj)){
		markj=marks[selectj]
		re=sum(fun(marki,markj))
		
		return(re)
	}else{
		return(0)
	}
}

pcfConvert=function(pk){
	pre.pk=pk
	pk=pk[!is.na(pk[,2]),]
	r=pk[,1]
	#y=pk[,2]/(2*pi*r)
	y=pk[,2]
	z=y/(pi*r^2)
	
	z[!is.finite(z)] <- 1
	ss <- ss <- smooth.spline(x = r, y = z)
	dz <- predict(ss, r, deriv = 1)$y
	g <- (r/2) * dz + z
	#g=dz
	re=data.frame(r,g)
	if(dim(re)[1]!=dim(pre.pk)[1]){
		r=pre.pk[,1]
		g=c(g,rep(NA,length(r)-length(g)))
		re=cbind(r,g)
	}
	return(re)
}

